<template>
    <div class="job-form-container">
        <div class="header-bar">
            <h2>{{ isEdit ? '编辑任务' : '创建任务' }}</h2>
            <el-button @click="goBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
                返回
            </el-button>
        </div>

        <el-card shadow="never">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" size="default">
                <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="任务名称" prop="taskName">
                            <el-input v-model="formData.taskName" placeholder="请输入任务名称" maxlength="50"
                                show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="任务状态" prop="status">
                            <el-select v-model="formData.status" placeholder="请选择状态">
                                <el-option label="活跃" value="ACTIVE" />
                                <el-option label="暂停" value="PAUSED" />
                                <el-option label="停止" value="STOPPED" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="任务描述" prop="description">
                    <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入任务描述"
                        maxlength="200" show-word-limit />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="目标类名" prop="targetClass">
                            <el-input v-model="formData.targetClass"
                                placeholder="例: com.example.tasks.HelloWorldTask" />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="目标方法" prop="targetMethod">
                            <el-input v-model="formData.targetMethod" placeholder="例: sayHello" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="Cron表达式" prop="cronExpression">
                    <el-input v-model="formData.cronExpression" placeholder="例: 0/30 * * * * ? (每30秒执行一次)" />
                    <div class="form-help">
                        <span>常用表达式：</span>
                        <el-button link type="primary" @click="setCronExpression('0 0/1 * * * ?')">
                            每分钟
                        </el-button>
                        <el-button link type="primary" @click="setCronExpression('0 0/5 * * * ?')">
                            每5分钟
                        </el-button>
                        <el-button link type="primary" @click="setCronExpression('0 0 0/1 * * ?')">
                            每小时
                        </el-button>
                        <el-button link type="primary" @click="setCronExpression('0 0 9 * * ?')">
                            每天9点
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item label="方法参数">
                    <el-input v-model="formData.methodParams" type="textarea" :rows="3"
                        placeholder='JSON格式参数，例: ["参数1", "参数2"] 或 [] (无参数)' />
                    <div class="form-help">
                        <span>参数格式：JSON数组，例如 ["Hello", "World"] 或 [1, 2] 或 [] (无参数)</span>
                    </div>
                </el-form-item>

                <el-form-item label="Java文件路径">
                    <el-input v-model="formData.javaFilePath" placeholder="热插拔Java文件路径 (可选)" />
                    <div class="form-help">
                        <span>用于热插拔功能，如：/path/to/hotplug-tasks/com/example/tasks/HelloWorldTask.java</span>
                        <el-button link type="primary" @click="showCodeEditor = true">
                            在线编辑
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSubmit" :loading="submitting" size="large">
                        {{ isEdit ? '更新任务' : '创建任务' }}
                    </el-button>
                    <el-button @click="handleReset" size="large">重置</el-button>
                    <el-button @click="goBack" size="large">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 示例任务快速选择 -->
        <el-card shadow="never" style="margin-top: 20px;">
            <template #header>
                <span>示例任务模板</span>
            </template>
            <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                    <el-card class="example-card" @click="loadExample('hello')">
                        <h4>Hello World 任务</h4>
                        <p>简单的Hello World示例</p>
                    </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                    <el-card class="example-card" @click="loadExample('backup')">
                        <h4>数据备份任务</h4>
                        <p>数据处理和备份示例</p>
                    </el-card>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                    <el-card class="example-card" @click="loadExample('monitor')">
                        <h4>系统监控任务</h4>
                        <p>系统健康检查示例</p>
                    </el-card>
                </el-col>
            </el-row>
        </el-card>
    </div>

    <!-- 在线代码编辑器对话框 -->
    <el-dialog v-model="showCodeEditor" title="在线代码编辑器" width="90%" :close-on-click-modal="false">
        <CodeEditor ref="codeEditorRef" v-model="editorContent" v-model:file-path="editorFilePath" height="600px"
            @saved="handleEditorSaved" @compiled="handleEditorCompiled" />

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showCodeEditor = false">关闭</el-button>
                <el-button type="primary" @click="useEditorContent">使用此文件</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { jobTaskApi } from '@/api/jobs'
import CodeEditor from '@/components/CodeEditor.vue'
import { fileApi } from '@/api/files'

const router = useRouter()
const route = useRoute()
const formRef = ref()

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)
const taskId = computed(() => route.params.id)

// 响应式数据
const submitting = ref(false)
const showCodeEditor = ref(false)
const editorContent = ref('')
const editorFilePath = ref('')

const codeEditorRef = ref()

// 表单数据
const formData = reactive({
    taskName: '',
    description: '',
    cronExpression: '',
    targetClass: '',
    targetMethod: '',
    methodParams: '',
    javaFilePath: '',
    status: 'ACTIVE'
})

// 表单验证规则
const formRules = {
    taskName: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    cronExpression: [
        { required: true, message: '请输入Cron表达式', trigger: 'blur' }
    ],
    targetClass: [
        { required: true, message: '请输入目标类名', trigger: 'blur' }
    ],
    targetMethod: [
        { required: true, message: '请输入目标方法名', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择任务状态', trigger: 'change' }
    ]
}

// 设置Cron表达式
const setCronExpression = (expression) => {
    formData.cronExpression = expression
}

// 加载示例任务
const loadExample = (type) => {
    const examples = {
        hello: {
            taskName: 'Hello World 任务',
            description: '简单的Hello World示例任务',
            cronExpression: '0/30 * * * * ?',
            targetClass: 'com.example.tasks.HelloWorldTask',
            targetMethod: 'sayHello',
            methodParams: '[]',
            javaFilePath: '/Users/wangbingbing/htmlProject/job_task/java/hotplug-tasks/com/example/tasks/HelloWorldTask.java'
        },
        backup: {
            taskName: '数据备份任务',
            description: '定期数据备份处理任务',
            cronExpression: '0 0 2 * * ?',
            targetClass: 'com.example.tasks.DataProcessingTask',
            targetMethod: 'backupData',
            methodParams: '[]',
            javaFilePath: '/Users/wangbingbing/htmlProject/job_task/java/hotplug-tasks/com/example/tasks/DataProcessingTask.java'
        },
        monitor: {
            taskName: '系统监控任务',
            description: '系统健康状态检查任务',
            cronExpression: '0 0/10 * * * ?',
            targetClass: 'com.example.tasks.SystemMonitorTask',
            targetMethod: 'healthCheck',
            methodParams: '[]',
            javaFilePath: '/Users/wangbingbing/htmlProject/job_task/java/hotplug-tasks/com/example/tasks/SystemMonitorTask.java'
        }
    }

    const example = examples[type]
    if (example) {
        Object.assign(formData, example)
    }
}

// 加载任务数据（编辑模式）
const loadTaskData = async () => {
    if (!isEdit.value) return

    try {
        const response = await jobTaskApi.getTaskById(taskId.value)
        const task = response.data
        Object.assign(formData, {
            taskName: task.taskName || '',
            description: task.description || '',
            cronExpression: task.cronExpression || '',
            targetClass: task.targetClass || '',
            targetMethod: task.targetMethod || '',
            methodParams: task.methodParams || '',
            javaFilePath: task.javaFilePath || '',
            status: task.status || 'ACTIVE'
        })
    } catch (error) {
        ElMessage.error('加载任务数据失败')
        console.error('加载任务数据失败:', error)
    }
}

// 提交表单
const handleSubmit = async () => {
    try {
        const valid = await formRef.value.validate()
        if (!valid) return

        submitting.value = true

        if (isEdit.value) {
            await jobTaskApi.updateTask(taskId.value, formData)
            ElMessage.success('任务更新成功')
        } else {
            await jobTaskApi.createTask(formData)
            ElMessage.success('任务创建成功')
        }

        goBack()
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitting.value = false
    }
}

// 重置表单
const handleReset = () => {
    formRef.value.resetFields()
    if (isEdit.value) {
        loadTaskData()
    }
}

// 返回列表页
const goBack = () => {
    router.push('/jobs')
}

// 组件挂载时加载数据
onMounted(() => {
    if (isEdit.value) {
        loadTaskData()
    }

    // 检查是否有路由参数
    if (route.query.targetClass) {
        formData.targetClass = route.query.targetClass
    }
    if (route.query.javaFilePath) {
        formData.javaFilePath = route.query.javaFilePath
    }
})

// 编辑器保存处理
const handleEditorSaved = ({ filePath, content }) => {
    formData.javaFilePath = filePath
    ElMessage.success('文件保存成功，已更新文件路径')
}

// 编辑器编译处理
const handleEditorCompiled = (filePath) => {
    ElMessage.success('文件编译成功')
}

// 使用编辑器内容
const useEditorContent = () => {
    if (editorFilePath.value) {
        formData.javaFilePath = editorFilePath.value

        // 尝试从文件路径推断类名
        if (!formData.targetClass) {
            const fileName = editorFilePath.value.split('/').pop().replace('.java', '')
            formData.targetClass = `com.example.tasks.${fileName}`
        }

        showCodeEditor.value = false
        ElMessage.success('已使用选中的Java文件')
    } else {
        ElMessage.warning('请先保存文件')
    }
}
</script>

<style scoped>
.job-form-container {
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 5px;
}

.header-bar h2 {
    margin: 0;
    color: #303133;
}

/* 表单卡片优化 */
:deep(.el-card__body) {
    padding: 15px;
}

:deep(.el-form) {
    width: 100%;
}

/* 表单帮助文本 */
.form-help {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
}

.form-help .el-button {
    padding: 0;
    margin-left: 8px;
    height: auto;
    font-size: 12px;
}

/* 示例卡片优化 */
.example-card {
    cursor: pointer;
    transition: all 0.3s;
    height: 100px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.example-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.example-card h4 {
    margin: 0 0 8px 0;
    color: #303133;
}

.example-card p {
    margin: 0;
    color: #606266;
    font-size: 13px;
}

/* 响应式布局 */


@media (max-width: 768px) {
    .job-form-container {
        padding: 0 10px;
    }

    .header-bar {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;
    }

    .header-bar h2 {
        font-size: 18px;
    }

    :deep(.el-form-item__label) {
        width: 100px !important;
        font-size: 14px;
    }

    :deep(.el-form-item__content) {
        margin-left: 100px !important;
    }

    .form-help {
        font-size: 11px;
    }

    .form-help .el-button {
        font-size: 11px;
        margin-left: 6px;
    }

    .example-card {
        height: 80px;
        margin-bottom: 15px;
    }

    .example-card h4 {
        font-size: 14px;
        margin-bottom: 5px;
    }

    .example-card p {
        font-size: 12px;
    }
}

@media (max-width: 480px) {
    .job-form-container {
        padding: 0;
    }

    .header-bar {
        padding: 0;
        margin-bottom: 10px;
    }

    .header-bar h2 {
        font-size: 16px;
    }

    .header-bar .el-button {
        font-size: 12px;
        padding: 6px 12px;
    }

    .header-bar .el-button span {
        display: none;
    }

    :deep(.el-card__body) {
        padding: 10px;
    }

    :deep(.el-form-item) {
        margin-bottom: 15px;
    }

    :deep(.el-form-item__label) {
        width: 80px !important;
        font-size: 12px;
        line-height: 1.2;
    }

    :deep(.el-form-item__content) {
        margin-left: 80px !important;
    }

    :deep(.el-input__inner),
    :deep(.el-textarea__inner) {
        font-size: 14px;
    }

    :deep(.el-select) {
        width: 100%;
    }

    .form-help {
        font-size: 10px;
        margin-top: 3px;
    }

    .form-help .el-button {
        font-size: 10px;
        margin-left: 4px;
        padding: 0;
    }

    /* 按钮组优化 */
    :deep(.el-form-item:last-child .el-form-item__content) {
        display: flex;
        flex-direction: column;
        gap: 10px;
    }

    :deep(.el-form-item:last-child .el-button) {
        width: 100%;
        margin: 0;
    }

    .example-card {
        height: 70px;
        margin-bottom: 10px;
    }

    .example-card h4 {
        font-size: 13px;
        margin-bottom: 3px;
    }

    .example-card p {
        font-size: 11px;
        line-height: 1.2;
    }

    /* 对话框优化 */
    :deep(.el-dialog) {
        width: 98% !important;
        margin: 2vh auto !important;
    }

    :deep(.el-dialog__body) {
        padding: 10px;
    }
}

/* 表单项垂直布局优化 */
@media (max-width: 600px) {
    :deep(.el-form-item) {
        display: flex;
        flex-direction: column;
    }

    :deep(.el-form-item__label) {
        width: 100% !important;
        margin-bottom: 5px;
        text-align: left !important;
    }

    :deep(.el-form-item__content) {
        margin-left: 0 !important;
        width: 100%;
    }
}
</style>